<template>
  <div
          @dragstart.prevent
          :class="['el-input-number', textAlign,
        { 'is-disabled': disabled },
      ]">
    <el-input
            ref="input"
            :value="currentValue"
            :placeholder="placeholder"
            :disabled="disabled"
            :maxlength="maxlength"
            :max="max"
            :min="min"
            :name="name"
            :label="label"
            @blur="handleBlur"
            @focus="handleFocus"
            @input="handleInput">
    </el-input>
  </div>
</template>
<script>

export default {
  name: 'WNumberInput',
  props: {
    max: {
      type: Number,
      default: Infinity,
    },
    min: {
      type: Number,
      default: -Infinity,
    },
    // eslint-disable-next-line no-bitwise,vue/require-prop-type-constructor
    value: String | Number,
    disabled: Boolean,
    name: String,
    textAlign: {
      type: String,
      default: 'text-align-left',
    },
    maxlength: Number,
    label: String,
    placeholder: String,
    precision: {
      type: Number,
      validator(val) {
        return val >= 0 && val === parseInt(val, 10);
      },
    },
  },
  data() {
    return {
      currentValue: '',
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(value) {
        this.setCurrentValue(value);
      },
    },
  },
  methods: {
    toPrecision(num, precision) {
      if (num === '' || num === undefined || num === null) return '';
      const val = (String(num).match(new RegExp(`^\\d+(?:\\.[0-9.]{0,${precision}})?`)));
      if (val) return val[0];
      return '';
    },
    handleInput(value) {
      this.setCurrentValue(value);
    },
    setCurrentValue(newVal) {
      const oldVal = this.currentValue;

      if (newVal === null || isNaN(newVal)) return; // 判断其是否为合法输入

      if (newVal > 0 && this.precision !== undefined) {
        newVal = this.toPrecision(newVal, this.precision);
      }

      if (newVal === oldVal) return;

      this.$emit('input', newVal);
      this.$emit('change', newVal, oldVal);

      this.currentValue = newVal;
    },
    handleBlur(event) {
      this.$emit('blur', event);
    },
    handleFocus(event) {
      this.$emit('focus', event);
    },
  },
};
</script>

<style lang="scss" scoped>
  .text-align-center{
    ::v-deep .el-input__inner{
      text-align: center;
    }
  }
  .text-align-left{
    ::v-deep .el-input__inner{
      text-align: left;
      font-size: 14px;
    }
  }
  .text-align-left, .text-align-center {
    ::v-deep .el-input__inner::placeholder{
      font-size: 14px;
      opacity: 0.5;
    }
    ::v-deep .el-input__inner{
      width: 400px;
      height: 30px;
      box-sizing: border-box;
      font-size: 20px;
      line-height: 30px;
      padding: 4px 0;
      background-color: rgba(0, 0, 0, 0);
      border: none;
      color: #fff;
    }
  }
</style>
